<?php
namespace \application\datatypes;

class RepeatSchedule extends DataType {
	public static $name = 'Repeat Schedule';
	public static $fields = array();
	
	public static function validate($field, $data, $results) {
		$schedules = $data[$field->cf_column];
		
		$count = count($schedules);
		if($required && !$count) {
			$results['errors'][] = $field->cf_display_name . ' - At least one repeat schedule is required.';
		}
		$i = 0;
		foreach($schedules as $schedule) {
			
				$i++;;
				/** Validate dates and times */
				$rptStart = strtotime($schedule['startdate'] . ' '.$schedule['starttime']);
				$rptEnd = strtotime($schedule['endtime']);
				
				/** If start is after end, the end is the next day. Otherwise, same day */
				if(strtotime($schedule['starttime']) >= $rptEnd) {
					$rptEnd = strtotime($schedule['startdate'] . ' '.$schedule['endtime']) + 60*60*24;
				}
				else {
					$rptEnd = strtotime($schedule['startdate'] . ' '.$schedule['endtime']);
				}
				
				if(!$rptStart) {
					$results['errors'][] = $field->cf_display_name . $i.' - Starting date and/or starting time are invalid.';
				}
				if(!$rptEnd) {
					$results['errors'][] = $field->cf_display_name . $i.' - Ending time is invalid.';
				}
			
				$results['db_fields'][$field->cf_column][]['sched_rpt_start'] = date('Y-m-d H:i:s', $rptStart);
				$results['db_fields'][$field->cf_column][]['sched_rpt_end'] = date('Y-m-d H:i:s', $rptEnd);
					
				/** Now check repeat modes */
				
				if($schedule['rpt_mode'] == 'every') {
				
					/** Make sure they pressed at least one checkbox */			
						
					$rptMode = $schedule['rpt_mon'].$schedule['rpt_tue'].$schedule['rpt_wed'].$schedule['rpt_thu'].$schedule['rpt_fri'].$schedule['rpt_sat'].$schedule['rpt_sun'];
					if(!$rptMode) {
						$results['errors'][] = $field->cf_display_name . $i.' - You must check at least one day to repeat on.';
					}
				}
				else {
					$rptMode = $schedule['rpt_mode'];
				}
				$results['db_fields'][$field->cf_column][]['sched_rpt_mode'] = $rptMode;
			
				if($rptMode) {
					/** Make sure rpt_for is numeric */
					if(!is_numeric($schedule['rpt_for'])) {
						$results['errors'][] = $field->cf_display_name . $i.' - Please enter a valid number of '.strtolower($schedule['rpt_unit']) . ' to repeat for.';
					}
					$results['db_fields'][$field->cf_column][]['sched_rpt_for'] = $schedule['rpt_for'];
					$results['db_fields'][$field->cf_column][]['sched_rpt_unit'] = $schedule['rpt_unit'];
				}
			}
		}
		return $results;
	}
	public static function display($formElements) {
		<?php if($formElements['display']) : ?>
			<fieldset>
			<legend><?=$formElements['display']?> <?=$formElements['ajax_buttons']?></legend>
			<?php endif;?>
			<?php $count = count($formElements['elements']);
			$n = $formElements['current_num'];
			for($i=0;$i<$count;$i++) : $n++; $element = $formElements['elements'][$i];?>
				<div class="cn-rpt-schedule">
				<h3>Schedule <?=$n?> <?php if($n > 1) : ?><input type="button" value="X" class="scheduling_remove_repeat"/><?php endif;?></h3>
				<label>Start Date: <?=$element['startdate']?></label><br />
				<label>Start Time: <?=$element['starttime']?></label><br />
				<label>End Time: <?=$element['endtime']?></label><br />
				<label><?=$element['rpt_none']?> No Repeat</label><br />
				<label>
				<?=$element['rpt_every']?> Repeat Every  
				Mon <?=$element['rpt_mon']?> | Tue <?=$element['rpt_tue']?> | Wed <?=$element['rpt_wed']?> | Thu <?=$element['rpt_thu']?> | Fri <?=$element['rpt_fri']?> | Sat <?=$element['rpt_sat']?> | Sun <?=$element['rpt_sun']?>
				</label><br />
				<label><?=$element['rpt_monthly_nth']?> Repeat Monthly (nth ___day, e.g. 3rd Sunday)</label><br />
				<label><?=$element['rpt_monthly_day']?> Repeat Monthly (nth day, e.g. the 10th of every month)</label><br />
				<label><?=$element['rpt_yearly']?> Yearly</label><br />
				<label>Repeat for <?=$element['rpt_for']?> <?=$element['rpt_unit']?></label>
				</div>
				<?php
			endfor;
			echo $formElements['field_footer'];
			if($formElements['display']) : ?>
			</fieldset>
		<?php endif;
	}
	public static function build($field, $data) {
		$currentNum = $_REQUEST['current_num'];
		$column = $field->cf_column;
		/** Is it an AJAX request to display a new repeat schedule? */
		if($currentNum) {
			
			$num = $currentNum + 1;
			$min = $currentNum;
		}
		else {
			/** Get number of repeat schedules. First priority is REQUEST, second is listing */
			$min = 0;
			$num = count($data[$column]);
			if(!$num) $num = count($schedules);
			if(!$num) $num = 1;
			$ajaxButtons = '<input type="button" id="scheduling_add_repeat" value="+"/>';
			$fieldFooter = '<div id="scheduling_extra_repeats"></div>';
		}
		
		
		$formElements = array('column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'ajax_buttons'=>$ajaxButtons, 'field_footer'=>$fieldFooter, 'current_num'=>$currentNum, 'elements'=>array());
		
		for($i=$min;$i<$num;$i++) {
			// Dates & Times
			$startdate = $data[$column][$i]['startdate'];
			$starttime = $data[$column][$i]['starttime'];
			$endtime = $data[$column][$i]['endtime'];
			
			// Repeat Mode
			$rptNone = 'checked="checked"';
			$rptDaily = ($data[$column][$i]['rpt_mode'] == 'daily') ? 'checked="checked"' : '';
			$rptEvery = (preg_match('/mon|tue|wed|thu|fri|sat|sun/', $data[$column][$i]['rpt_mode'])) ? 'checked="checked"' : '';
			$rptMonthlyNth = ($data[$column][$i]['rpt_mode'] == 'monthly_nth') ? 'checked="checked"' : '';
			$rptMonthlyDay = ($data[$column][$i]['rpt_mode'] == 'monthly_day']) ? 'checked="checked"' : '';
			$rptYearly = ($data[$column][$i]['rpt_mode'] == 'yearly') ? 'checked="checked"' : '';
			
			// Days
			$rptMon = (strstr($data[$column][$i]['rpt_mode'], 'mon') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptTue = (strstr($data[$column][$i]['rpt_mode'], 'tue') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptWed = (strstr($data[$column][$i]['rpt_mode'], 'wed') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptThu = (strstr($data[$column][$i]['rpt_mode'], 'thu') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptFri = (strstr($data[$column][$i]['rpt_mode'], 'fri') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptSat = (strstr($data[$column][$i]['rpt_mode'], 'sat') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			$rptSun = (strstr($data[$column][$i]['rpt_mode'], 'sun') && !$rptMonthlyNth && !$rptMonthlyDay) ? 'checked="checked"' : '';
			
			// Time Limit
			$rptFor = $data[$column][$i]['rpt_for'];
			$rptUnitDays = ($data[$column][$i]['rpt_unit'] == 'DAY') : 'selected="selected"' : '';
			$rptUnitWeeks = ($data[$column][$i]['rpt_unit'] == 'WEEK') : 'selected="selected"' : '';
			$rptUnitMonths = ($data[$column][$i]['rpt_unit'] == 'MONTH') : 'selected="selected"' : '';
			$rptUnitYears = ($data[$column][$i]['rpt_unit'] == 'YEAR') : 'selected="selected"' : '';
			
			$formElements['elements'][] = array(
					'startdate'=>
						sprintf('<input type="text" value="%s" name="%s" id="%s" class="datepicker cn-rpt-schedule-marker"/>', $startdate, $column.'[][startdate]', $column.'_startdate'.$i),
					'starttime'=>
						sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker"/>', $starttime, $column.'[][starttime]', $column.'_starttime'.$i),
					'endtime'=>
						sprintf('<input type="text" value="%s" name="%s" id="%s" class="timepicker"/>', $endtime, $column.'[][endtime]', $column.'_endtime'.$i),
					
					'rpt_none'=>
						sprintf('<input type="radio" %s name="%s" id="%s" value=""/>', $rptNone, $column.'[][rpt_mode]', $column.'_rpt_none'.$i),
					'rpt_every'=>
						sprintf('<input type="radio" %s name="%s" id="%s" value="every"/>', $rptEvery, $column.'[][rpt_mode]', $column.'_rpt_every'.$i),
					'rpt_mon'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="mon"/>', $rptMon, $column.'[][rpt_mon]', $column.'_rpt_mon'.$i),
					'rpt_tue'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="tue"/>', $rptTue, $column.'[][rpt_tue]', $column.'_rpt_tue'.$i),
					'rpt_wed'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="wed"/>', $rptWed, $column.'[][rpt_wed]', $column.'_rpt_wed'.$i),
					'rpt_thu'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="thu"/>', $rptThu, $column.'[][rpt_thu]', $column.'_rpt_thu'.$i),
					'rpt_fri'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="fri"/>', $rptFri, $column.'[][rpt_fri]', $column.'_rpt_fri'.$i),
					'rpt_sat'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="sat"/>', $rptSat, $column.'[][rpt_sat]', $column.'_rpt_sat'.$i),
					'rpt_sun'=>
						sprintf('<input type="checkbox" %s name="%s" id="%s" value="sun"/>', $rptSun, $column.'[][rpt_sun]', $column.'_rpt_sun'.$i),
					
					'rpt_monthly_nth'=>
						sprintf('<input type="radio" %s name="%s" id="%s" value="monthly_nth"/>', $rptMonthlyNth, $column.'[][rpt_mode]', $column.'_rpt_monthly_nth'.$i),
					'rpt_monthly_day'=>
						sprintf('<input type="radio" %s name="%s" id="%s" value="monthly_day"/>', $rptMonthlyDay, $column.'[][rpt_mode]', $column.'_rpt_monthly_day'.$i),
					'rpt_yearly'=>
						sprintf('<input type="radio" %s name="%s" id="%s" value="yearly"/>', $rptYearly, $column.'[][rpt_mode]', $column.'_rpt_yearly'.$i),
					
					'rpt_for'=>
						sprintf('<input type="text" value="%s" name="%s" id="%s" class="short-text"/>', $rptFor, $column.'[][rpt_for]', $column.'_rpt_for'.$i),
					'rpt_unit'=>
						sprintf('<select name="%s" id="%s" class="repeat-unit"><option %s value="DAY">Days</option><option %s value="WEEK">Weeks</option><option %s value="MONTH">Months</option><option %s value="YEAR">Years</option></select>', $column.'[][rpt_unit]', $column.'_rpt_unit'.$i,$rptUnitDays, $rptUnitWeeks, $rptUnitMonths, $rptUnitYears)
			);
		}
		return $formElements;
	}
	
	public static function addSchedule($field) {
		$build = self::build($field, null);
		self::display($build);
	}
	
	public static function endForm($field, $data, $id, $type) {
		// Add/remove schedules and occurrences
		$schedules = $data[$field->cf_column];
		$cleanSchedules = array();
		foreach($schedules as $key=>$schedule) {
			$schedule['sched_id'] = $id;
			$schedules[$key] = $schedule;
			$cleanSchedules[$key] = array('sched_id'=>$id, 'sched_rpt_start'=>$schedule['sched_rpt_start'], 'sched_rpt_end'=>$schedule['sched_rpt_end'], 'sched_rpt_mode'=>$schedule['sched_rpt_mode']);
		}
		
		if($id) { // Check for removal
			
			// Get previously existing schedules
			$existing = DB()->getResults("SELECT `sched_id`, `sched_rpt_start`, `sched_rpt_end`, `sched_rpt_mode FROM `repeat_schedules` WHERE `sched_content`='$id'", 'array');
			
			$scheduleCombine = array();
			$existingCombine = array();
			foreach($cleanSchedules as $key=>$schedule) {
				$scheduleCombine[$key] = implode('|', $schedule);
			}
			foreach($existing as $schedule) {
				$temp = $schedule;
				array_shift($temp);
				$existingCombine[$schedule['sched_id']] = implode('|', $temp);
			}
			
			
			// Get previously existing schedules
			
			// Get schedules that we don't have to add/remove
			$noNeed = array_intersect($scheduleCombine, $existingCombine);
			
			// Get schedules we need to remove
			$toDelete = array_diff($existingCombine, $noNeed);
			
			//$toDelete = "'".implode("', '", $toDelete)."'";
			
			// Get schedules we need to add
			$toAdd = array_diff($scheduleCombine, $existingCombine);
			
			$toAdd = array_keys($toAdd);
			$noNeed = array_keys($noNeed);
			$deleteArray = array_keys($toDelete);
			$deleteArray = "'".implode("', '", $deleteArray)."'";
			
			$addArray = array();
			foreach($toAdd as $add) {
				$addArray[] = $schedules[$add];
			}
		}
		else {
			$addArray = $schedules;
		}
		
		// Delete and add
		if(count($toDelete))
		
		
	}
	
	public static function add() {}
	public static function save() {}
	public static function endForm() {}
	public static function delete() {}
	
	public static function formJS($field) {}
	public static function displayJS() {}
	public static function customHeader() {}
	
	public static function fromDB($fields, $field, $data) {
		$column = $field->cf_column;
		return array($field->cf_column => $fields[$column]);
	}
	
	public static function prepareData($field, $data, $params) {
		return $data[$field->cf_column];
	}

}

?>